Delete selected items from bound ListBox in C#

chris (2004-11-16 13:42:46)
4993 views
0 replies
With complex databinding, the display of multiple data objects in Windows Forms components is managed automatically, but adding and removing new items to a bound DataSet can appear more difficult. Well actually it's quite easy. This example shows a ListBox which is bound to a DataSet (which incidentally is read in from an XML string). A Button_Click method is shown to illustrate how the selected rows in the ListBox are then deleted.

/* first the dataset is created */
/* in this example, resultXML is a string containing some xml data */

_dataset = new DataSet();
_dataset.ReadXml(new StringReader(resultXML));

/* bind the listbox to the dataset */
_listBox1.ValueMember = "id";
_listBox1.DisplayMember = "name";
_listBox1.DataSource = _dataset.Tables["address"];

So at this stage the listbox has been created and bound to the 'address' table within the dataset. A sample xml object which would fit this example might be:

-<result>
     -<addresses>
      -<address id="1" name="fred" email="fred@test.com">
      -<address id="2" name="barney" email="barney@test.com">
      -<address id="2" name="wilma" email="wilma@test.com">
     -</addresses>
-</result>

Anyway, the point of this is to illustrate how you might delete the rows from a multi-selectable listbox. If a button is set up with a Click event handler to carry out the deletion, the method might look something like this:

/* obtain a reference to the datatable which serves as the data source for the listbox */
/* remember this was set up a little earlier as _dataset.Tables["address"] */

DataTable MyDataTable = (DataTable)_listBox1.DataSource;

/* get an arraylist of references to the selected rows */
/* then iterate and delete selected items from listbox */

ArrayList _arrayList = new ArrayList(_listBox1.SelectedIndices);
for(int i = _arrayList.Count; i>0; i--){
      int _target = i-1;
      MyDataTable.Rows.RemoveAt((int)_arrayList[_target]);
}

You will find that all the selected rows then disappear - Note that the deletion didn't occur at the UI level. It all took place at the dataset level (MyDataTable.Rows.RemoveAt), but the binding ensures that the data display is kept up to date. This means that you don't have to write call refresh() methods every time the data is updated.

Hope that's useful,


christo
comment